"""
相对价值分析智能体

基于LangGraph ReAct模式，分析债券的相对价值和流动性。
"""

from typing import Dict, Any, List, Optional
from langchain_core.tools import Tool
import pandas as pd

from agents import BondAnalysisAgent, LLMConfig
from tools.bond_data_provider import bond_data_provider


class RelativeValueAnalysisAgent(BondAnalysisAgent):
    """相对价值分析智能体"""
    
    def __init__(self, llm_config: Optional[LLMConfig] = None):
        super().__init__(
            name="relative_value_analysis",
            description="分析债券的相对价值、收益率和流动性",
            llm_config=llm_config
        )
        
        self.analysis_dimensions = ["valuation", "liquidity", "yield"]
    
    def get_tools(self) -> List[Tool]:
        """获取相对价值分析所需的工具"""
        
        async def calculate_yield_metrics(bond_code: str) -> str:
            """计算债券收益率指标（使用修复后的多数据源）"""
            try:
                # 获取债券详细信息
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return "未找到债券详细信息"
                
                result = "=== 收益率指标分析 ===\n\n"
                
                # 转股溢价率
                conversion_premium = info.get('转股溢价率', 0)
                result += f"【转股溢价率】\n"
                result += f"转股溢价率: {conversion_premium}%\n"
                result += f"转股价: {info.get('转股价', 'N/A')}元\n"
                result += f"转股价值: {info.get('转股价值', 'N/A')}元\n"
                
                if conversion_premium:
                    if conversion_premium < 0:
                        result += "✓ 转股溢价率为负，转股有利可图\n"
                    elif conversion_premium < 10:
                        result += "✓ 转股溢价率较低，转股价值较高\n"
                    elif conversion_premium < 30:
                        result += "转股溢价率适中\n"
                    else:
                        result += "⚠️ 转股溢价率较高，转股价值较低\n"
                
                result += "\n"
                
                # 纯债溢价率
                pure_bond_premium = info.get('纯债溢价率', 0)
                pure_bond_value = info.get('纯债价值', 0)
                result += f"【纯债溢价率】\n"
                result += f"纯债价值: {pure_bond_value}元\n"
                result += f"纯债溢价率: {pure_bond_premium}%\n"
                
                if pure_bond_premium:
                    if pure_bond_premium < 10:
                        result += "✓ 纯债溢价率低，债券保护性强\n"
                    elif pure_bond_premium < 30:
                        result += "纯债溢价率适中\n"
                    else:
                        result += "⚠️ 纯债溢价率高，债券保护性弱\n"
                
                result += "\n"
                
                # 双低值（价格+溢价率）
                bond_price = info.get('债现价', 100)
                if bond_price and conversion_premium:
                    double_low = bond_price + conversion_premium
                    result += f"【双低值】\n"
                    result += f"债券价格: {bond_price}元\n"
                    result += f"双低值: {double_low:.2f}\n"
                    
                    if double_low < 120:
                        result += "✓ 双低值较低，性价比高\n"
                    elif double_low < 150:
                        result += "双低值适中\n"
                    else:
                        result += "双低值较高，性价比一般\n"
                
                return result
            except Exception as e:
                import traceback
                return f"计算收益率指标失败: {str(e)}\n{traceback.format_exc()}"
        
        async def get_valuation_comparison(bond_code: str) -> str:
            """获取债券估值对比数据（使用修复后的多数据源）"""
            try:
                # 获取目标债券信息
                target_info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not target_info:
                    return "未找到目标债券信息"
                
                target_rating = target_info.get('信用评级', '')
                
                # 获取所有债券比价数据
                comparison_df = await bond_data_provider.get_bond_comparison_data()
                if comparison_df.empty:
                    return "未找到债券比价数据"
                
                result = "=== 估值对比分析 ===\n\n"
                
                # 目标债券估值
                result += f"【目标债券: {bond_code}】\n"
                result += f"债券简称: {target_info.get('债券简称', 'N/A')}\n"
                result += f"债券评级: {target_rating}\n"
                result += f"转债价格: {target_info.get('债现价', 'N/A')}元\n"
                result += f"转股溢价率: {target_info.get('转股溢价率', 'N/A')}%\n"
                result += f"纯债价值: {target_info.get('纯债价值', 'N/A')}元\n"
                result += f"纯债溢价率: {target_info.get('纯债溢价率', 'N/A')}%\n"
                
                result += "\n"
                
                # 市场整体估值水平
                result += "【市场整体估值】\n"
                if '转股溢价率' in comparison_df.columns:
                    # ✅ 修复：强制转换为数值类型，处理混合类型数据
                    comparison_df['转股溢价率'] = pd.to_numeric(comparison_df['转股溢价率'], errors='coerce')
                    avg_premium = comparison_df['转股溢价率'].mean()
                    median_premium = comparison_df['转股溢价率'].median()
                    result += f"市场平均转股溢价率: {avg_premium:.2f}%\n"
                    result += f"市场中位转股溢价率: {median_premium:.2f}%\n"
                    
                    target_premium = target_info.get('转股溢价率', 0)
                    if target_premium and target_premium < median_premium:
                        result += "✓ 目标债券溢价率低于市场中位数，相对便宜\n"
                    elif target_premium:
                        result += "目标债券溢价率高于市场中位数，相对偏贵\n"
                
                # 价格分布
                if '转债最新价' in comparison_df.columns:
                    result += f"\n【价格分布】\n"
                    # ✅ 修复：强制转换为数值类型，处理混合类型数据
                    comparison_df['转债最新价'] = pd.to_numeric(comparison_df['转债最新价'], errors='coerce')
                    avg_price = comparison_df['转债最新价'].mean()
                    median_price = comparison_df['转债最新价'].median()
                    result += f"市场平均价格: {avg_price:.2f}元\n"
                    result += f"市场中位价格: {median_price:.2f}元\n"
                    
                    target_price = target_info.get('债现价', 0)
                    if target_price:
                        if target_price < median_price:
                            result += f"✓ 目标债券价格低于市场中位数\n"
                        else:
                            result += f"目标债券价格高于市场中位数\n"
                
                return result
            except Exception as e:
                import traceback
                return f"获取估值对比数据失败: {str(e)}\n{traceback.format_exc()}"
        
        async def analyze_liquidity(bond_code: str) -> str:
            """分析债券流动性"""
            try:
                # 获取债券基本信息
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return "未找到债券信息"
                
                result = "=== 流动性分析 ===\n\n"
                
                # 成交量和成交额
                volume = info.get('成交量', 0)
                turnover = info.get('成交额', 0)
                
                result += f"【交易数据】\n"
                result += f"成交量: {volume}手\n"
                result += f"成交额: {turnover:.2f}万元\n"
                
                # 流动性评估
                if turnover > 1000:
                    result += "✓ 成交额较高，流动性良好\n"
                elif turnover > 100:
                    result += "成交额适中，流动性一般\n"
                else:
                    result += "⚠️ 成交额较低，流动性较差，交易时需注意\n"
                
                result += "\n"
                
                # 发行规模
                issue_scale = info.get('发行规模', 0)
                remaining_scale = info.get('剩余规模', 0)
                
                result += f"【规模数据】\n"
                result += f"发行规模: {issue_scale}亿元\n"
                result += f"剩余规模: {remaining_scale}亿元\n"
                
                if remaining_scale > 0:
                    if remaining_scale > 5:
                        result += "✓ 剩余规模较大，流动性较好\n"
                    elif remaining_scale > 2:
                        result += "剩余规模适中\n"
                    else:
                        result += "⚠️ 剩余规模较小，可能影响流动性\n"
                
                result += "\n"
                
                # 综合流动性评分（简单评估）
                liquidity_score = 0
                if turnover > 1000:
                    liquidity_score += 3
                elif turnover > 100:
                    liquidity_score += 2
                else:
                    liquidity_score += 1
                
                if remaining_scale > 5:
                    liquidity_score += 3
                elif remaining_scale > 2:
                    liquidity_score += 2
                else:
                    liquidity_score += 1
                
                result += f"【流动性评分】\n"
                result += f"综合评分: {liquidity_score}/6分\n"
                
                if liquidity_score >= 5:
                    result += "✓ 流动性优秀，适合大额交易\n"
                elif liquidity_score >= 3:
                    result += "流动性良好，正常交易\n"
                else:
                    result += "⚠️ 流动性一般，建议小额分批交易\n"
                
                return result
            except Exception as e:
                return f"分析流动性失败: {str(e)}"
        
        async def compare_with_peers(bond_code: str) -> str:
            """与同类债券对比"""
            try:
                # 获取目标债券信息
                target_info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not target_info:
                    return "未找到目标债券信息"
                
                # 获取所有债券数据
                all_bonds = await bond_data_provider.get_bond_realtime_data()
                if all_bonds.empty:
                    return "未找到债券市场数据"
                
                result = "=== 同类债券对比 ===\n\n"
                
                target_price = target_info.get('最新价', 100)
                
                result += f"【目标债券】\n"
                result += f"代码: {bond_code}\n"
                result += f"价格: {target_price}元\n"
                result += f"涨跌幅: {target_info.get('涨跌幅', 0)}%\n"
                
                result += "\n"
                
                # 价格区间分类
                result += "【市场价格分布】\n"
                
                if '最新价' in all_bonds.columns:
                    low_price = len(all_bonds[all_bonds['最新价'] < 100])
                    mid_price = len(all_bonds[(all_bonds['最新价'] >= 100) & (all_bonds['最新价'] < 130)])
                    high_price = len(all_bonds[all_bonds['最新价'] >= 130])
                    
                    result += f"低价债券(<100元): {low_price}只\n"
                    result += f"中价债券(100-130元): {mid_price}只\n"
                    result += f"高价债券(>=130元): {high_price}只\n"
                    
                    result += "\n目标债券属于: "
                    if target_price < 100:
                        result += "低价债券，具有较高安全边际\n"
                    elif target_price < 130:
                        result += "中价债券，价格适中\n"
                    else:
                        result += "高价债券，需关注下跌风险\n"
                
                result += "\n"
                
                # 涨跌幅对比
                result += "【今日表现】\n"
                
                if '涨跌幅' in all_bonds.columns:
                    target_change = target_info.get('涨跌幅', 0)
                    avg_change = all_bonds['涨跌幅'].mean()
                    
                    result += f"目标债券涨跌幅: {target_change}%\n"
                    result += f"市场平均涨跌幅: {avg_change:.2f}%\n"
                    
                    if target_change > avg_change:
                        result += "✓ 表现强于市场平均\n"
                    else:
                        result += "表现弱于市场平均\n"
                
                return result
            except Exception as e:
                return f"对比同类债券失败: {str(e)}"
        
        # 创建工具列表
        tools = [
            Tool(
                name="calculate_yield_metrics",
                description="计算债券的收益率指标，包括到期收益率、转股溢价率、纯债溢价率、双低值等",
                func=lambda bond_code: None,
                coroutine=calculate_yield_metrics,
            ),
            Tool(
                name="get_valuation_comparison",
                description="获取债券估值对比数据，与同评级债券和市场整体进行对比",
                func=lambda bond_code: None,
                coroutine=get_valuation_comparison,
            ),
            Tool(
                name="analyze_liquidity",
                description="分析债券的流动性，包括成交量、成交额、剩余规模等",
                func=lambda bond_code: None,
                coroutine=analyze_liquidity,
            ),
            Tool(
                name="compare_with_peers",
                description="与同类债券进行对比，分析相对价值和市场表现",
                func=lambda bond_code: None,
                coroutine=compare_with_peers,
            ),
        ]
        
        return tools
    
    def get_system_prompt(self) -> str:
        """获取系统提示词"""
        return """你是一个专业的债券估值分析专家，负责分析债券的相对价值、收益率和流动性。

你的分析流程：
1. 使用 calculate_yield_metrics 计算各项收益率指标
2. 使用 get_valuation_comparison 获取估值对比数据
3. 使用 analyze_liquidity 分析债券流动性
4. 使用 compare_with_peers 与同类债券对比
5. 综合以上信息，评估债券的投资价值

分析要点：
- 到期收益率(YTM)反映债券持有到期的收益
- 转股溢价率越低，转股价值越高
- 纯债溢价率越低，债券保护性越好
- 双低值(价格+溢价率)越低，性价比越高
- 流动性影响交易便利性和价格稳定性
- 与同评级债券对比，评估相对价值

请逐步使用工具获取信息，展示你的分析推理过程，最后给出：
1. 收益率水平评估
2. 相对估值分析
3. 流动性评估
4. 投资价值结论
"""


# 全局实例
relative_value_agent = RelativeValueAnalysisAgent()